<template>
    <div class="shopping-chart-body">
        <!-- 购物车描述行 -->
        <div class="chart-desc-line">
            <span>我的购物车</span>
            <span>共{{ Object.keys($store.state.shoppingCartList).length > 0 ? $store.state.shoppingCartList.length : 0 }}门课程</span>
        </div>

        <!-- 购物车列表 -->
        <a-table :row-selection="rowSelection" :columns="columns" :data-source="$store.state.shoppingCartList"
            :rowKey="record => record.course.courseId" :pagination="false">
            <!-- 课程封面 -->
            <template slot="cover" slot-scope="text, record">
                <img :src="record.course.coverFileUrl" alt="课程封面"
                    style="width: 80px; height: 60px; object-fit: cover; border-radius: 4px;" />
            </template>

            <!-- 课程名称 -->
            <a slot="name" slot-scope="text">{{ text }}</a>

            <!-- 课程价格 -->
            <template slot="price" slot-scope="text, record">
                <span v-if="record.course.isFree == 1" class="free">免费</span>
                <span class="price" v-else>
                    ￥{{ record.course.isDiscount == 0 ? record.course.coursePrice : record.course.discountPrice }}
                </span>
                <span class="old-price" v-if="record.course.isFree != 1 && record.course.isDiscount == 1">
                    ￥{{ record.course.coursePrice }}
                </span>
            </template>

            <!-- 优惠 -->
            <template slot="discount" slot-scope="record">
                <span v-if="record.isDiscount == 0" class="origin-price">原价</span>
                <span v-if="record.isFree != 1 && record.isDiscount == 1" class="discount-info">限时钜惠</span>
            </template>

            <!-- 操作 -->
            <template slot="action" slot-scope="record">
                <a-popconfirm title="确定删除该课程吗？" ok-text="确定" cancel-text="取消" @confirm="clickDeleteCourse(record)">
                    <a-icon type="delete" />
                </a-popconfirm>
            </template>
        </a-table>

        <!-- 购物车底部 -->
        <div class="bottom-line">
            <div class="select-all">
                <a-checkbox :checked="isAllSelected" @change="handleSelectAll">
                    全选
                </a-checkbox>
            </div>

            <div class="total-price">
                合计：￥<span>{{ selectedTotal }}</span>
            </div>

            <div>提交</div>
        </div>
    </div>
</template>

<script>
import { getLoginUserInfo, getUserShoppingCartInfo, deleteChartCourse } from "@/api/request";

export default {
    name: 'ShoppingCharBody',
    data() {
        return {
            columns: [
                {
                    title: '课程封面',
                    dataIndex: 'course.coverFileUrl',
                    scopedSlots: { customRender: 'cover' },
                },
                {
                    title: '课程名称',
                    dataIndex: 'course.courseTitle',
                    scopedSlots: { customRender: 'name' },
                },
                {
                    title: '课程价格',
                    dataIndex: 'course.price',
                    scopedSlots: { customRender: 'price' },
                },
                {
                    title: '优惠',
                    dataIndex: 'course',
                    scopedSlots: { customRender: 'discount' },
                },
                {
                    title: '操作',
                    dataIndex: 'shoppingCartId',
                    scopedSlots: { customRender: 'action' },
                },
            ],
            visible: false,
            deleteModalVisible: {},
            selectedRowKeys: [], // 添加选中行的key数组
        }
    },

    methods: {
        clickGetUserLoginInfo() {
            getLoginUserInfo().then(res => {
                console.log('clickGetUserLoginInfo', res);
            });
        },

        clickGetUserShoppingCartInfo() {
            console.log('clickGetUserShoppingCartInfo');
            
            getUserShoppingCartInfo().then(res => {
                console.log('getUserShoppingCartInfo', res);
                this.$store.commit('setShoppingCartList', res.shoppingCartList);
            })
        },

        // 删除课程
        async clickDeleteCourse(shoppingCartId) {
            console.log('deleteCourse', shoppingCartId);
            // 删除课程
            await deleteChartCourse(shoppingCartId).then((result) => {
                console.log('deleteChartCourse', result);
            }).catch((err) => {
                console.log(err);
            });
            // 刷新购物车信息
            await this.clickGetUserShoppingCartInfo();
        },

        // 处理全选/取消全选
        handleSelectAll(e) {
            if (e.target.checked) {
                // 全选
                this.selectedRowKeys = this.$store.state.shoppingCartList.map(item => item.course.courseId);
            } else {
                // 取消全选
                this.selectedRowKeys = [];
            }
        }
    },

    created() {
        // 若处于登录状态，则获取购物车信息
        if (this.$store.state.userInfo && Object.keys(this.$store.state.userInfo).length > 0) {
            this.clickGetUserShoppingCartInfo();
        }
    },

    computed: {
        rowSelection() {
            return {
                selectedRowKeys: this.selectedRowKeys,
                onChange: (selectedRowKeys, selectedRows) => {
                    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                    this.selectedRowKeys = selectedRowKeys;
                },
                getCheckboxProps: record => ({
                    props: {
                        disabled: record.name === 'Disabled User',
                        name: record.name,
                    },
                }),
            };
        },

        // 计算是否全选
        isAllSelected() {
            return this.$store.state.shoppingCartList.length > 0 &&
                this.selectedRowKeys.length === this.$store.state.shoppingCartList.length;
        },

        // 计算选中课程的总金额
        selectedTotal() {
            if (this.selectedRowKeys.length === 0) {
                return 0;
            }
            const selectedItems = this.$store.state.shoppingCartList.filter(item =>
                this.selectedRowKeys.includes(item.course.courseId)
            );

            let total = selectedItems.reduce((sum, item) => {
                if (item.course.isFree == 1) {
                    return sum; 
                } else if (item.course.isDiscount == 1) {
                    return sum + item.course.discountPrice; 
                } else {
                    return sum + item.course.coursePrice; 
                }
            }, 0);

            return total;
        }
    }
}
</script>

<style lang="less" scoped>
.shopping-chart-body {
    background: #fff;
    width: 1160px;
    margin: 0 auto;
}

.chart-desc-line {
    padding: 10px;

    >span:first-of-type {
        font-size: 16px;
        margin-right: 10px;
    }
}

.free {
    color: #00cf8c;
    font-weight: 600;
    font-size: 16px;
}

.price {
    font-weight: 500;
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Helvetica Neue, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;
    font-variant: tabular-nums;
    line-height: 1.5;
}

.old-price {
    color: #999;
    text-decoration: line-through;
    font-size: 12px;
}

.origin-price {
    color: #fff;
    background: rgb(16, 142, 233);
    padding: 5px 7px;
    font-size: 12px;
    box-sizing: border-box;
}

.discount-info {
    color: #fff;
    background: rgb(255, 94, 13);
    padding: 5px 7px;
    font-size: 12px;
    box-sizing: border-box;
}

.bottom-line {
    width: 1160px;
    height: 60px;
    background: rgb(238, 238, 238);
    display: flex;
    align-items: center;

    .select-all {
        width: 100px;
        padding-left: 20px;
    }

    >.total-price {
        flex: 1;
        text-align: right;
        line-height: 60px;

        >span {
            color: red;
            margin-right: 20px;
        }
    }

    >div:nth-of-type(3) {
        width: 120px;
        font-size: 20px;
        line-height: 60px;
        text-align: center;
        background: rgb(255, 128, 0);
    }
}
</style>